package com.wetalk.gateway.filter;

import com.wetalk.gateway.Config.AuthProperties;
import com.wetalk.gateway.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Slf4j
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("过滤器拦截到了请求");
        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse resp = exchange.getResponse();
        //获取url
        String url = req.getPath().toString();
        log.info("请求的url:{}", url);
        //判断是否不需要拦截
        if (url.contains("login") || url.contains("register") || url.contains("all")|| url.contains("remoting")) {
            log.info("登录或注册操作，或远程调用操作，放行");
            return chain.filter(exchange);
        }
        //获取令牌
        String jwt = null;
        List<String> headers = req.getHeaders().get("Authorization");
        if(headers!=null && !headers.isEmpty()){
            jwt = headers.get(0);
        }
        log.info(jwt);
        //判断令牌
        if (!StringUtils.hasLength(jwt)) {
            log.info("令牌为空，无效");
            error(resp);
            return resp.setComplete();
        }
        Claims claims;
        //解析令牌
        try {
            claims = JwtUtils.jwtRead(jwt);
        } catch (Exception e) {//失败
            e.printStackTrace();
            log.info("解析失败");
            error(resp);
            return resp.setComplete();
        }
        //传递用户id信息
        String userInfo= claims.get("id").toString();
        //在原有的exchange信息的前提下重构
        ServerWebExchange ex=exchange.mutate()
                //重新向请求头中添加用户信息
                .request(b-> b.header("userInfo",userInfo))
                .build();

        log.info("令牌合法，放行");
        return chain.filter(ex);
    }

    private static void error(ServerHttpResponse resp) {
        log.info("解析令牌失败, 返回未登录错误信息");

//        // 创建一个错误结果
//        usersResult error = usersResult.error("NOT_LOGIN");

        // 设置 HTTP 状态码为 401 Unauthorized
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);


        // 将错误结果转换为 JSON 并返回
//        String notLogin = JSONObject.toJSONString(error);
//        resp.setContentType("application/json;charset=UTF-8");
//        resp.getWriter().write(notLogin);
    }


    @Override
    public int getOrder() {
        // 过滤器执行顺序，值越小，优先级越高
        return 0;
    }
}